package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.ExplorSumBean;
import com.hongxun.design.bean.ExplorSumListBean;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.PointSumBean;
import com.hongxun.design.bean.PointSumRouteBean;
import com.hongxun.design.bean.SpanBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.titlepopupwindow.BitTypeBean;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zerdoor_pc on 2016/6/2.
 * 项目首页二级地图界面
 */
public class ProjectMapSecondActivity extends BaseActivity implements HeadSecond {
    private String projectName;
    TextView words;
    List<BitTypeBean> bitTypeBeans = new ArrayList<>();
    String number;
    String explor_id = "", explor_name;
    HeadSecondControlPanel headsecond_layout;
    ExplorSumBean bean;
    PointSumBean sysbean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_projectmapsecond);
        findBar();
        findView();
        initialization();
    }

    @SuppressLint("NewApi")
    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        number = bundle.getString(MString.number, "");
        explor_id = bundle.getString(MString.TYPE, "");
        projectName = bundle.getString(MString.name, "");
        projectType = bundle.getString(MString.CODE, "");
        explor_name = bundle.getString(MString.explor_name, "");
    }

    @Override
    public void findBar() {
        getIntentData();
        headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.projectmaps_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.VISIBLE, R.color.login_yellow, ListenerSet.back, projectName, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        SetTypeface.set(headsecond_layout.mRightTitle, IconSourse.DAOHANG);
        headsecond_layout.mRightTitle.append(" 导航");
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pointData.size() > 0) {
                    if (msgstring.length() == 0) {
                        ToastShow.showShort(mActivity, "系统异常");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString(MString.TYPE, explor_id);
                    bundle.putString(MString.number, number);
                    bundle.putString(MString.CODE, msgstring);
                    IntentToActivity.intent(mActivity, NavigationActivity.class, bundle);
                } else {
                    ToastShow.showShort(mActivity, "没有点位数据");
                }


            }
        });
    }

    boolean isfirstin = true;

    @Override
    protected void onResume() {
        MyApp.ChangeToOldProject();
        MyApp.activity = this;
        mActivity = this;
        MyApp.BackActivity = 0;

        MyApp.currExploration.clear();
        if (!isfirstin) {
            MyApp.HTTP.http.isLoad = false;
            getExplorationList();//获取点位列表
        } else {
            isfirstin = false;
        }

        headsecond_layout.setTitle(MyApp.currProject.getProject_name());
        if (baidumapstyle != null) baidumapstyle.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (baidumapstyle != null) baidumapstyle.onPause();
        super.onPause();
    }


    @Override
    protected void findView() {
        super.findView();
        findViewAndInit_UI();
        findView_Data();
        findViewAndInit_MapButton();//初始化地图位置
    }

    @Override
    protected void initialization() {
        super.initialization();
        addPointSumHandler();
        addPointHandler();
        /**取用缓存数据**/
//        String ExplorSumJson = MyApp.File.ReadFileData(MString.ProjectStageTransformerTotalInfo + "_" + MyApp.currProject.getStage_id() + "_" + explor_id);
//        if (ExplorSumJson != null && ExplorSumJson.length() > 0) {
//            bean = FastJsonUtil.JsonToGetExplorSum(ExplorSumJson);
//            pointSumHandler.sendEmptyMessage(1);
//        }
        //MyApp.File.ReadFileToSend(pointSumHandler, MString.ProjectStageTransformerTotalInfo + "_" + MyApp.currProject.getStage_id() + "_" + explor_id);

        getExplorSum();//获取台区详情信息
        //getTransformerList();//获取台区
        //getExplorationList();//获取点位列表
        //isnewlyBuild(newlybuild);
        getExplorationList();
    }


    /**
     * *************************************数据请求*****************************************************************
     */
    /**
     * 获取台区详情信息*
     */
    private void getExplorSum() {
        if (MyApp.isOnLine) {
            if (explor_id.equals("-1")) {
                MyApp.HTTP.getPointSum(pointSumHandler, 2, MyApp.currProject.getStage_id(), explor_id);
            } else {
                MyApp.HTTP.getExplorSum(pointSumHandler, HttpStringUtil.SUCCESSED, explor_id);
            }
        } else {

        }
    }


    /**
     * 获取点位列表*
     */
    private void getExplorationList() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.getExplorationList(pointHandler, HttpStringUtil.SUCCESSED, projectType, MyApp.currProject.getStage_id(), explor_id);//获取踏勘点列表
        } else {
            if (pointData == null) {
                pointData = GetFileUtil.getExplorationList(projectType);
            } else {
                pointData.clear();
                pointData.addAll(GetFileUtil.getExplorationList(projectType));
            }
            msgstring = GetFileUtil.getExplorationListString(projectType);
            pointHandler.sendEmptyMessage(3);
        }


    }


    /**
     * *************************************数据请求接收器*****************************************************************
     */
    private Handler pointSumHandler;
    private Handler pointHandler;

    /**
     * 项目详情信息接收器*
     */
    private void addPointSumHandler() {
        pointSumHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED: {
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
//                            bean = FastJsonUtil.JsonToGetPointSum((String) msg.obj);
                            bean = FastJsonUtil.JsonToGetExplorSum((String) msg.obj);
                            pointSumHandler.sendEmptyMessage(1);
                        }
                    }
                    break;
                    case 2: {
                        String s = "";
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            sysbean = FastJsonUtil.JsonToGetPointSum((String) msg.obj);

                            if (sysbean != null) {
                                if (sysbean.trans_num != null)
                                    s += "变压器:" + sysbean.trans_num + "台";
                                if (sysbean.pole_num != null) s += " 杆:" + sysbean.pole_num + "基";
                                if (sysbean.user_num != null) s += " 用电户:" + sysbean.user_num + "户";
                                if (sysbean.route != null && sysbean.route.size() > 0) {
                                    for (PointSumRouteBean b : sysbean.route) {
                                        String voltageGrade = DataUtil.getStringFormSystemTypeBean(HttpStringCodeTableUtil.voltageGrade, b.voltage_grade);
                                        if (voltageGrade.length() > 0) {
                                            try {
                                                if (b.line_length != null && b.line_length.length() > 0) {
                                                    s += "\n" + voltageGrade + "线路:";
                                                    s += b.line_length + "Km";
                                                }
                                                if (b.line_pole != null && b.line_pole.length() > 0) {
                                                    s += " 杆塔:" + b.line_pole + " 基";
                                                }
                                            } catch (Exception e) {
                                            }
                                        }

                                    }
                                }

                            }
                        } else {
                        }
                        currS = s;
                        words.setText(s);
                    }
                    break;

                    case 1: {
                        String s = "";
                        if (bean != null) {
                            List<SystemTypeBean> transCapacitylist = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.transCapacity);
                            for (SystemTypeBean t : transCapacitylist) {
                                if (t.getTypecode().equals(bean.trans_capacity)) {
                                    s += "额定容量:" + t.getTypename();
                                    break;
                                }
                            }

                            s += " 杆塔:" + bean.pole_num + "基";
                            if (bean.route != null && bean.route.size() > 0) {
                                for (ExplorSumListBean b : bean.route) {
                                    String voltageGrade = DataUtil.getStringFormSystemTypeBean(HttpStringCodeTableUtil.voltageGrade, b.voltage_grade);
                                    if (voltageGrade.length() > 0) {
                                        try {

                                            if (b.line_length != null && b.line_length.length() > 0) {
                                                s += "\n" + voltageGrade + "线路:";
                                                s += b.line_length + "Km";
                                            }
                                            if (b.line_pole != null && b.line_pole.length() > 0) {
                                                s += " 杆塔:" + b.line_pole + " 基";
                                            }

                                        } catch (Exception e) {
                                        }
                                    }


                                }
                            }

                        }
                        currS = s;
                        words.setText(s);
                    }
                    break;
                    case HttpStringUtil.ERROR: {
                        if (MyApp.isOnLine) {
                            ToastShow.showShort(mActivity, (String) msg.obj);
                        }
                    }
                    break;

                }
            }
        };
    }


    String currS = "";

    /**
     * 点位列表信息接收器*
     */
    List<Exploration> pointData;

    String msgstring = "";

    private void addPointHandler() {
        if (pointHandler == null) pointHandler = new Handler() {


            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            msgstring = (String) msg.obj;
                            if (pointData == null) {
                                pointData = FastJsonUtil.JsonToGetExplorationList((String) msg.obj);
                            } else {
                                pointData.clear();
                                pointData.addAll(FastJsonUtil.JsonToGetExplorationList((String) msg.obj));
                            }

                            pointHandler.sendEmptyMessage(3);
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:
                        flag = true;
                        addPoint(pointData);
                        break;
                    case 2:
                        if (span) {
                            addSpan();
                        }

                        break;
                    case 3:
                        try {
                            List<Exploration> point = new ArrayList<>();
                            // String Before_exp="";
                            point.clear();
                            if (explor_id.length() == 0) {
                                for (Exploration b : pointData) {
                                    if (b.getVoltage_grade().equals("101")) {
                                        point.add(b);
                                    }
                                }
                            } else {
                                for (Exploration b : pointData) {
                                    if ((b.pt_type.equals(MString.DWD) && !b.getFlag().equals(MString.del) && explor_id.length() > 0 && b.getExplor_id().equals(explor_id)) || MString.getValueId(b.getExploration_id(), b.getUuid()).equals(explor_id)) {
                                        if (MString.getValueId(b.getExploration_id(), b.getUuid()).equals(explor_id)) {
                                            //   Before_exp=b.getBefore_exp();
                                            b.setBefore_lng("");
                                            b.setBefore_lat("");
                                            b.setBefore_exp("");
                                        }
                                        point.add(b);
                                    }
                                }
                            }

                            pointData.clear();
                            pointData.addAll(point);
                        } catch (Exception e) {

                        }
                        pointHandler.sendEmptyMessage(1);
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;

                }
            }
        };
    }


    /**
     * 加载点位并画出线段*
     */
    boolean flag = true;
    List<SpanBean> points = new ArrayList<>();

    private synchronized void addPoint(final List<Exploration> pointData) {
        flag = true;
        mBaiduMap.clear();
        points.clear();
        baidumapstyle.clearmarker_Seconds();
        if (pointData == null || pointData.size() == 0) {
            if (currentPt == null) {
                try {
                    currentPt = new LatLng(Double.parseDouble(MyApp.currProject.getLat()), Double.parseDouble(MyApp.currProject.getLng()));
                } catch (Exception e) {
                    currentPt = null;
                }
            }
            if (currentPt == null) return;
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(currentPt).zoom(MyApp.zoom).build()));
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
            return;
        }
        baidumapstyle.projectType = projectType;
        baidumapstyle.setPointClick(2);
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Map<String, Integer> map = DataUtil.getIconData(0);
                    for (Exploration exploration : pointData) {
                        if (exploration.lat != null && exploration.lng != null && exploration.lat.length() > 0 && exploration.lng.length() > 0) {
                            LatLng point = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                            if (flag) {
                                flag = false;
                                try {

                                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(point).zoom(MyApp.zoom).build()));
                                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
                                } catch (Exception e) {
                                }
                            }

                            if (corner) {
                                baidumapstyle.addMarka(exploration, getApplicationContext(), point, Integer.parseInt(map.get(exploration.pt_id).toString()));
                            } else {
                                baidumapstyle.addMarka(exploration, point, Integer.parseInt(map.get(exploration.pt_id).toString()));
                            }
                            if (!exploration.getPt_id().equals(MString.Transformer) && exploration.before_lat != null && exploration.before_lng != null && exploration.before_lat.length() > 0 && exploration.before_lng.length() > 0) {
                                LatLng p1 = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                                LatLng p2 = new LatLng(Double.parseDouble(exploration.before_lat), Double.parseDouble(exploration.before_lng));
                                points.add(new SpanBean(new LatLng((p1.latitude + p2.latitude) / 2, (p1.longitude + p2.longitude) / 2), exploration.distance));
                                List<LatLng> points = new ArrayList<LatLng>();
                                points.add(p1);
                                points.add(p2);
                                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                                        .color(R.color.red).points(points);
                                Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
                            }
                        }

                    }

                    pointHandler.sendEmptyMessage(2);
                }
            }).start();
        } catch (Exception e) {
        }


    }

    /****************************************地图设置******************************************************************/
    /**
     * 显示与隐藏按钮*
     */
    public void disPlay(View view) {
        LinearLayout setpoint_inf_item = (LinearLayout) findViewById(R.id.projectmaps_inf_item);
        if (setpoint_inf_item.getVisibility() == View.VISIBLE) {
            setpoint_inf_item.setVisibility(View.GONE);
            ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.fold));
        } else {
            setpoint_inf_item.setVisibility(View.VISIBLE);
            ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.unfold));
        }
    }

    /**
     * 设置地图*
     */
    public MapView mMapView;
    public BaiduMap mBaiduMap;
    public MBaiduMap baidumapstyle;
    public static LatLng currentPt;//选定的点位

    private void findViewAndInit_MapButton() {
        /***档距与转角**/
        check_span = (SimpleDraweeView) findViewById(R.id.check_span);
        check_corner = (SimpleDraweeView) findViewById(R.id.check_corner);
        /**新建与拆旧**/

        baidumapstyle = (MBaiduMap) findViewById(R.id.baidumapstyle);
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        baidumapstyle.hidePosition();
        if (currentPt == null) return;
        baidumapstyle.setMarka(currentPt);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(currentPt).zoom(MyApp.zoom).build()));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
    }

    /**
     * 设置界面基础ui*
     */
    private void findViewAndInit_UI() {
        TextView reconnaissanceButton = (TextView) findViewById(R.id.projectmaps_bottom_reconnaissancebutton);
        TextView detailedButton = (TextView) findViewById(R.id.projectmaps_bottom_detailedbutton);
        SetTypeface.set(reconnaissanceButton, IconSourse.TASHE);
        SetTypeface.set(detailedButton, IconSourse.DETAILED);
        reconnaissanceButton.append(" 点位采集");
        detailedButton.append(" 查看明细");
        if (MyApp.ReadOnly) {
            reconnaissanceButton.setBackgroundResource(R.drawable.inputbox_gray_4);
        }

    }

    /**
     * 设置数据控件*
     */
    private void findView_Data() {
        TextView bottom_title = (TextView) findViewById(R.id.projectmaps_bottom_title);
        words = (TextView) findViewById(R.id.projectmaps_bottom_words1);
        words.setMovementMethod(ScrollingMovementMethod.getInstance());
        bottom_title.setText(number);
    }


    private String getDesignStage(String code) {
        List<SystemTypeBean> designStage = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.designStage);//设计阶段
        for (SystemTypeBean s : designStage) {
            if (s.getTypecode().equals(code)) {
                return s.getTypename();
            }
        }
        return "";
    }


    /**点击方法**/
    /**
     * 踏勘*
     */
    public void Reconnaissance(View v) {
        if (MyApp.ReadOnly) {

        } else {
            IntentToActivity.intent(mActivity, ReconnaissanceActivity.class);
        }
    }

    /**
     * 项目详情*
     */
    public void details(View v) {
        Bundle bundle = new Bundle();
        bundle.putString(MString.TextTYPE, "1");
        bundle.putString(MString.explor_id, explor_id);
        bundle.putString(MString.number, explor_name);
        bundle.putString(MString.exploration_type, projectType);
        IntentToActivity.intent(mActivity, ProjectDetailsActivity.class, bundle);
    }

    /**
     * 档距与转角*
     */
    SimpleDraweeView check_span, check_corner;
    boolean span = false;
    boolean corner = false;

    //档距
    public void span(View v) {
        if (span) {
            span = false;
            check_span.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.displayspan));
            addPoint(pointData);
            MyLog.L(MString.SUCCESSED + " 档距span=" + span);
        } else {
            span = true;
            check_span.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.hiddenspan));
            addSpan();
        }
    }

    private void addSpan() {
        MyLog.L(MString.SUCCESSED + " 档距points=" + JSON.toJSONString(points));
        MyLog.L(MString.SUCCESSED + " 档距span=" + span);
        if (points.size() > 0) {
            for (SpanBean s : points) {
                if (!(s.distance == null || s.distance.length() == 0)) {
                    baidumapstyle.addMarka(mActivity, s.distance, s.point);
                }

            }
        }
    }

    //转角
    public void corner(View v) {
        if (corner) {
            corner = false;
            check_corner.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.displaycorner));
            addPoint(pointData);
        } else {
            corner = true;
            check_corner.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.hiddencorner));
            addPoint(pointData);
        }
    }


    /**
     * 新建与拆旧*
     */
    boolean buldeflag = true;

    public void isnewlyBuild(View v) {
        if (buldeflag) {
            //新建
            buldeflag = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.newcheck));
            projectType = "11";
        } else {
            //拆旧
            buldeflag = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.oldcheck));
            projectType = "12";
        }
        getExplorationList();
    }

    public static String projectType = "11";


    @Override
    protected void onDestroy() {
        if (baidumapstyle != null) baidumapstyle.onDestroy();
        super.onDestroy();
    }
}
